package gee

import "strings"

// Node
//参数匹配:。例如 /p/:lang/doc，可以匹配 /p/c/doc 和 /p/go/doc。
//通配*。例如 /static/*filepath，可以匹配/static/fav.ico，
//也可以匹配/static/js/jQuery.js，这种模式常用于静态服务器，能够递归地匹配子路径。
type Node struct {
	pattern   string //待匹配
	part      string
	children  []*Node //子节点
	isPerfect bool    //是否是精准匹配
}

//搜索某个节点
func (node *Node) searchPrefix(part string) *Node {
	for _, child := range node.children {
		if child.part == part || child.isPerfect {
			return child
		}
	}
	return nil
}

//搜索某个节点的全节点路径
func (node *Node) searchDirs(part string) (nodes []*Node) {
	nodes = make([]*Node, 0)
	for _, child := range node.children {
		if child.part == part || child.isPerfect {
			nodes = append(nodes, child)
		}
	}
	return
}

//递归的插入节点
func (node *Node) insert(pattern string, parts []string, height int) {
	if len(parts) == height {
		node.pattern = pattern
		return
	}
	part := parts[height]
	child := node.searchPrefix(part)
	if child == nil {
		child = &Node{part: part, isPerfect: part[0] == ':' || part[0] == '*'}
		node.children = append(node.children, child)
	}
	child.insert(pattern, parts, height+1)
}

//搜索某一组路由是否符合规则
func (node *Node) search(parts []string, height int) *Node {
	if len(parts) == height || strings.HasPrefix(node.part, "*") {
		if len(node.pattern) == 0 {
			return nil
		}
		return node
	}
	part := parts[height]
	children := node.searchDirs(part)
	for _, child := range children {
		result := child.search(parts, height+1)
		if result != nil {
			return result
		}
	}
	return nil
}
